package com.website.dayouziblog.intercepter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.web.servlet.config.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private LoginIntercepter loginIntercepter;

    @Value("${interceptor}")
    private Boolean interceptor;


    /**
     * 解决跨域问题
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
//                .allowedOrigins("*")
                .allowedOriginPatterns("*")
                .allowCredentials(true);
    }

    /**
     * 异步请求配置
     * @param configurer
     */
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(3)));
        configurer.setDefaultTimeout(30000);
    }


    /**
     * 配置拦截器、拦截路径
     * 每次请求到拦截的路径，就会去执行拦截器中的方法
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //配置放行路径
        List<String> excludePath = new ArrayList<>();
        //login
        excludePath.add("/login");
        //regist
        excludePath.add("/regist");
        //swagger
        excludePath.add("/doc.html");
        excludePath.add("/swagger-ui.html");
        excludePath.add("/swagger-resources/**");
        excludePath.add("/v2/api-docs");
        excludePath.add("/webjars/**");
        excludePath.add("/static/**");
        excludePath.add("/assets/**");

        //根据不同环境配置是否需要token校验
        if (interceptor){
            registry.addInterceptor(loginIntercepter)
                    .addPathPatterns("/**")
                    .excludePathPatterns(excludePath);
        }else {
            registry.addInterceptor(loginIntercepter)
                    .excludePathPatterns("/**");
        }

        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
